package com.lyl.servicelive.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyl.exception.ZxjyException;
import com.lyl.servicelive.entity.Course;
import com.lyl.servicelive.entity.Visitor;
import com.lyl.servicelive.mapper.CourseMapper;
import com.lyl.servicelive.mapper.VisitorMapper;
import com.lyl.servicelive.mtcloud.CommonResult;
import com.lyl.servicelive.mtcloud.MTCloud;
import com.lyl.servicelive.service.VisitorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 直播来访者记录表 服务实现类
 * </p>
 *
 * @author 雷艳玲
 * @since 2022-07-05
 */
@Service
public class VisitorServiceImpl extends ServiceImpl<VisitorMapper, Visitor> implements VisitorService {

    @Autowired
    CourseMapper courseMapper;

    @Resource
    private MTCloud mtCloudClient;
    @Override
    public List<Visitor> selectListByCourseId(Long id) {
        QueryWrapper<Visitor> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("live_course_id",id);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public List<Visitor> getVistors(Long id) {

            // 已经有观看记录了,无需下载
            List<Visitor> visitors= selectListByCourseId(id);
            if(visitors!=null && visitors.size()>0){
                return visitors;
            }

            HashMap<Object, Object> options = new HashMap<>();
            Course liveCourse = courseMapper.selectById(id);
            try {
                String res = mtCloudClient.courseVisitorList(liveCourse.getCourseId().toString(),1,10,options);
                System.out.println("res:"+res);

                //返回结果转换，判断是否成功
                CommonResult<JSONArray> commonResult = JSON.parseObject(res, CommonResult.class);
                if(Integer.parseInt(commonResult.getCode()) == MTCloud.CODE_SUCCESS) {

                    JSONArray array = commonResult.getData();
                    visitors=new ArrayList<>();
                    // 获取观看记录, 并插入到表中
                    for (int i = 0; i <array.size() ; i++) {
                        JSONObject vis= array.getJSONObject(i);

                        Visitor visitor= new Visitor();
                        visitor.setLiveVisitorId(vis.getString("id"));

                        visitor.setJoinTime(vis.getString("join_time"));
                        visitor.setLeaveTime(vis.getString("leave_time"));
                        visitor.setDurationTime(vis.getString("duration_time"));
                        visitor.setDuration(vis.getLong("duration"));
                        visitor.setNickName(vis.getString("name"));
                        visitor.setLocation(vis.getString("location"));
                        visitor.setUserId(vis.getString("uid"));

                        visitor.setCourseName(liveCourse.getCourseName());
                        visitor.setLiveCourseId(liveCourse.getCourseId());
                        visitors.add(visitor);
                    }
                    saveBatch(visitors);

                    return visitors;

                } else {
                    throw new ZxjyException(20001,commonResult.getmsg());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return  null;

    }

    @Override
    public void pageQuery(Page<Visitor> pageParam, Long courseId) {
        QueryWrapper<Visitor> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("live_course_id",courseId);
        // 删除之前的数据
        this.remove(queryWrapper);


            HashMap<Object, Object> options = new HashMap<>();
            Course liveCourse = courseMapper.selectById(courseId);
            try {
                String res = mtCloudClient.courseVisitorList(liveCourse.getCourseId().toString(),1,10,options);
                System.out.println("res:"+res);
                List<Visitor> visitors=null;
                //返回结果转换，判断是否成功
                CommonResult<JSONArray> commonResult = JSON.parseObject(res, CommonResult.class);
                if(Integer.parseInt(commonResult.getCode()) == MTCloud.CODE_SUCCESS) {

                    JSONArray array = commonResult.getData();
                    visitors=new ArrayList<>();
                    // 获取观看记录, 并插入到表中
                    for (int i = 0; i <array.size() ; i++) {
                        JSONObject vis= array.getJSONObject(i);

                        Visitor visitor= new Visitor();
                        visitor.setLiveVisitorId(vis.getString("id"));

                        visitor.setJoinTime(vis.getString("join_time"));
                        visitor.setLeaveTime(vis.getString("leave_time"));
                        visitor.setDurationTime(vis.getString("duration_time"));
                        visitor.setDuration(vis.getLong("duration"));
                        visitor.setNickName(vis.getString("name"));
                        visitor.setLocation(vis.getString("location"));
                        visitor.setUserId(vis.getString("uid"));
                        visitor.setCourseName(liveCourse.getCourseName());
                        visitor.setLiveCourseId(liveCourse.getId());
                        visitors.add(visitor);
                    }
                    saveBatch(visitors);
                    baseMapper.selectPage(pageParam, queryWrapper);

                } else {
                    throw new ZxjyException(20001,commonResult.getmsg());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    }
}
